package cn.sc.summer.mybatis.config.tableconfig;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.sc.summer.mybatis.table.execute.ServerExecute;
import cn.sc.summer.mybatis.config.superconfig.PackageConfig;
import cn.sc.summer.mybatis.constant.TableConstant;
import cn.sc.summer.mybatis.constant.TableResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 类名：执行器配置类
 *
 * @author a-xin
 * @date 2024/8/29 13:47
 */
@Slf4j
@Configuration
public class ExecuteConfig extends PackageConfig {

    @Bean(name = TableConstant.EXECUTE_UPDATE_BEAN)
    @ConditionalOnBean(name = {TableConstant.LOAD_JAVA_TABLE_INFO_BEAN})
    public Boolean executeUpdate() {
        if (CollUtil.isNotEmpty(TableResource.ALL_DATASOURCE_INFO)) {
            execute();
            TableResource.destroyResource();
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 执行数据源表格更新
     *
     */
    private void execute() {
        Map<String, ServerExecute> serverExecuteMap = SpringUtil.getBeansOfType(ServerExecute.class);
        if (CollUtil.isNotEmpty(serverExecuteMap)) {
            Map<String, ServerExecute> executeMap = new HashMap<>();
            serverExecuteMap.forEach((classType, execute) -> {
                String supports = execute.getSupports();
                if (CharSequenceUtil.isNotBlank(supports)) {
                    executeMap.put(supports, execute);
                }
            });

            TableResource.ALL_DATASOURCE_INFO.forEach(dataSourceX -> {
                String databaseProductName = dataSourceX.getDataSourceTypeName();
                log.info("==> Start performing a data source: [{}] -> [{}] table update!", dataSourceX.getDataSourceName(), databaseProductName);
                if (executeMap.containsKey(databaseProductName)) {
                    executeMap.get(databaseProductName).execute(dataSourceX);
                }
            });
        }
    }

}
